<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Model\Device;
use App\Model\DeviceThree;
use App\Model\DeviceTwo;
use App\Model\Group;
use App\Model\InverterData;
use App\Model\InverterDataThree;
use App\Model\InverterDataTwo;
use App\Model\Site;
use App\Model\StatisticsDayEnergy;
use Illuminate\Http\Request;

class SiteController extends Controller
{

    public function getEnergyData(Request $request)
    {
        $type = $request->input('type');
        $time_type = $request->input('time_type');
        $start = $request->input('start');
        $end = $request->input('end');

        $id = $request->input('id');

        $start_date = strtotime($start);
        $end_date = strtotime($end);

        $result = [];
        //电脑数据
        if ($type == 'energy') {
            $labels = [];
            $datas = [];

            if ($time_type == 'm') {
                $s_y = (int)date('Y', $start_date);
                $s_m = (int)date('m', $start_date);
                $e_y = (int)date('Y', $end_date);
                $e_m = (int)date('m', $end_date);
                $interval_month = 12 * ($e_y - $s_y) + ($e_m - $s_m);


                for ($i = 0; $i <= $interval_month; $i++) {
                    $m = date('Y-m', strtotime('+' . $i . ' month', $start_date));
                    array_push($labels, $m);
                    $energy = StatisticsDayEnergy::getOneMonthBySiteId($id, $m);
                    array_push($datas, $energy);
                }

            }
            if ($time_type == 'd') {
                $sdes = StatisticsDayEnergy::getSomeBySiteId($id, $start, $end);
                $labels = [];
                $datas = [];
                foreach ($sdes as $sde) {

                    array_push($labels, $sde->date);
                    array_push($datas, $sde->site_value);
                }
            }

            $result['labels'] = $labels;
            $result['data'] = $datas;
            return $this->json_success($result);
        }
        //功率数据
        if ($type == 'power') {
            //TODO
        }

        return $this->json_error('不支持的类型！', 1002);


    }

    public function getIndex(Request $request)
    {
        $user = $this->_getCurrentUser();

        $sites = Site::getSitesByUserId($user->id);

        foreach ($sites as $site) {
            //换算经纬度
            $positions = explode(',', $site->position);
            $site->position_lon = $positions[0];
            $site->position_lat = $positions[1];
        }

        return view('frontend.site.index', [
            'sites' => $sites
        ]);
    }

    public function getDetail(Request $request)
    {
        $id = $request->input('id');
        $site = Site::find($id);
        //换算经纬度
        $positions = explode(',', $site->position);
        $site->position_lon = $positions[0];
        $site->position_lat = $positions[1];
        switch ($id){
            case $id < 18:
                $working_devices_count = Device::getDevicesCountBySiteId($site->id);
                $result = InverterData::getDayMonthYearBySiteId($site->id);
                $group_count = Group::getGroupsTotalBySiteId($id);
                $device_count = Device::getDevicesCountBySiteId($id);
                $begin_date = date('Y-m-d', strtotime('-7 day'));
                $end_date = date('Y-m-d');
                break;
            case $id>=18 && $id<43:
                $working_devices_count = DeviceTwo::getDevicesCountBySiteId($site->id);
                $result = InverterDataTwo::getDayMonthYearBySiteId($site->id);
                $group_count = Group::getGroupsTotalBySiteId($id);
                $device_count = DeviceTwo::getDevicesCountBySiteId($id);
                $begin_date = date('Y-m-d', strtotime('-7 day'));
                $end_date = date('Y-m-d');
                break;
            default:
                $working_devices_count = DeviceThree::getDevicesCountBySiteId($site->id);
                $result = InverterDataThree::getDayMonthYearBySiteId($site->id);
                $group_count = Group::getGroupsTotalBySiteId($id);
                $device_count = DeviceThree::getDevicesCountBySiteId($id);
                $begin_date = date('Y-m-d', strtotime('-7 day'));
                $end_date = date('Y-m-d');
        }
        return view('frontend.site.detail', [
            'site' => $site,
            'group_count' => $group_count,
            'device_count' => $device_count,
            'working_devices_count' => $working_devices_count,
            'today_gen_cap' => $result['dayGen'],
            'month_gen_cap' => $result['monthGen'],
            'year_gen_cap' => $result['yearGen'],
            'total_gen_cap' => $result['totalGen'],
            'now_power' => $result['power'],
            'begin_date' => $begin_date,
            'end_date' => $end_date
        ]);


//        if($id < 18) {
//
//                $working_devices_count = Device::getDevicesCountBySiteId($site->id);
//                $result = InverterData::getDayMonthYearBySiteId($site->id);
////                $today_gen_cap = InverterData::getTodayGenCapBySiteId($site->id);
////                dump(4);
////                $month_gen_cap = InverterData::getMonthGenCapBySiteId($site->id);
//////                dump(5);
////                $total_gen_cap = InverterData::getTotalGenCapBySiteId($site->id);
////                //$year_gen_cap = InverterData::getYearGenCapBySiteId($site->id);
//////                dump(6);
////                $year_gen_cap = $total_gen_cap;
////
////                $now_power = InverterData::getNowPowerBySiteId($site->id) / 1000.0;
////
//                $group_count = Group::getGroupsTotalBySiteId($id);
//                $device_count = Device::getDevicesCountBySiteId($id);
//                 $begin_date = date('Y-m-d', strtotime('-7 day'));
//                 $end_date = date('Y-m-d');
//            return view('frontend.site.detail', [
//                'site' => $site,
//                'group_count' => $group_count,
//                'device_count' => $device_count,
//                'working_devices_count' => $working_devices_count,
//                'today_gen_cap' => $result['dayGen'],
//                'month_gen_cap' => $result['monthGen'],
//                'year_gen_cap' => $result['yearGen'],
//                'total_gen_cap' => $result['totalGen'],
//                'now_power' => $result['power'],
//                'begin_date' => $begin_date,
//                'end_date' => $end_date
//            ]);
//        }else {
//            $working_devices_count = DeviceTwo::getDevicesCountBySiteId($site->id);
//            $result = InverterDataTwo::getDayMonthYearBySiteId($site->id);
//            $group_count = Group::getGroupsTotalBySiteId($id);
//            $device_count = DeviceTwo::getDevicesCountBySiteId($id);
//            $begin_date = date('Y-m-d', strtotime('-7 day'));
//            $end_date = date('Y-m-d');
//            return view('frontend.site.detail', [
//                'site' => $site,
//                'group_count' => $group_count,
//                'device_count' => $device_count,
//                'working_devices_count' => $working_devices_count,
//                'today_gen_cap' => $result['dayGen'],
//                'month_gen_cap' => $result['monthGen'],
//                'year_gen_cap' => $result['yearGen'],
//                'total_gen_cap' => $result['totalGen'],
//                'now_power' => $result['power'] / 1000.0,
//                'begin_date' => $begin_date,
//                'end_date' => $end_date
//            ]);
//        }
    }

    public function getDevices(Request $request)
    {
        $id = $request->input('id');
        $site = Site::find($id);
        $site_id = $site->id;
        $groups = Group::getGroupsBySiteId($site->id);

        foreach ($groups as $group) {
//            if($site->id <18) {
//                $devices = Device::getDevicesByGroupId($group->id);
//            }else {
//                $devices = DeviceTwo::getDevicesByGroupId($group->id);
//            }
            switch ($site_id){
                case $site_id < 18:
                    $devices = Device::getDevicesByGroupId($group->id);
                    break;
                case $site_id >= 18 && $site_id < 43:
                    $devices = DeviceTwo::getDevicesByGroupId($group->id);
                    break;
                default:
                    $devices = DeviceThree::getDevicesByGroupId($group->id);
            }
            $group->devices = $devices;
            foreach ($devices as $device) {
//                if($site->id<18) {
//                    $ivd = InverterData::getLastInverterDataByDeviceId($site->user_id, $device->device_id);
//                }else {
//                    $ivd = InverterDataTwo::getLastInverterDataByDeviceId($site->user_id, $device->device_id);
//                }
                switch ($site_id){
                    case $site_id < 18:
                        $ivd = InverterData::getLastInverterDataByDeviceId($site->user_id, $device->device_id);
                        break;
                    case $site_id >= 18 && $site_id < 43:
                        $ivd = InverterDataTwo::getLastInverterDataByDeviceId($site->user_id, $device->device_id);
                        break;
                    default:
                        $ivd = InverterDataThree::getLastInverterDataByDeviceId($site->user_id, $device->device_id);
                }
                //status 1，2，3 正常，警报，离线

                //数据不存在则离线、功率为0
                if (!$ivd) {
                    $device->status = 3;
                    $device->power = 0;
                } else {
                    //最近一次数据为20分钟前则离线功率为0
                    $now = time();
                    $created_at = strtotime($ivd->created_at);
                    if ($now - $created_at > 60 * 60) {
                        $device->status = 3;
                        $device->power = 0;
                    } else {
                        $device->power = $ivd->ActivePower;
                        //最近一条数据为警报，则显示警报状态
                        //状态码小于等于3都是正常运行，具体请参考Helper::transError()
                        if ($ivd->IVStatus <= 3) {
                            $device->status = 1;
                        } else {
                            $device->status = 2;
                        }
                    }

                }


            }
        }

        return view('frontend.site.devices', ['groups' => $groups]);
    }

}
